/**
 * MIT License
 *
 * Copyright (c) 2024 小村程序员
 * Email: 397237738@qq.com
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package org.open.cobertura.core.analyzer;

import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Opcodes;
import org.open.cobertura.core.data.CoberturaExecutionData;
import org.open.cobertura.core.instrument.CoberturaClassProbeAdapter;
import org.open.cobertura.util.Crc64;
import org.open.cobertura.data.ICoberturaPackageCovered;
import org.open.cobertura.report.ICreateReport;
import org.open.cobertura.report.html.CreateHtmlReport;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;

/**
 * 分析报告
 */
public class CoberturaAnalyzer {

    /**
     * 创建报告
     * @param coberturaDataFile 探针数据文件
     * @param classFile 字节码文件
     */
    public void createCoberturaReport(final String coberturaDataFile,final String classFile,final String sourceFile){
        CoberturaReaderExecutionData coberturaReaderExecutionData=new CoberturaReaderExecutionData();
        CoberturaCoveredFactory coberturaCoveredFactory=new CoberturaCoveredFactory();
        CoberturaExecutionData coberturaExecutionData=coberturaReaderExecutionData.readerExecutionData(coberturaDataFile);
        analyzerAll(classFile,coberturaExecutionData,coberturaCoveredFactory);
        List<ICoberturaPackageCovered> coberturaPackageCovered=coberturaCoveredFactory.getCoberturaCovered();
        ICreateReport createReport=new CreateHtmlReport();
        createReport.createReport(coberturaPackageCovered,sourceFile);
    }

    /**
     * 分析所有的文件，支持读取整个字节码目录
     * @param classFile 类文件
     * @param coberturaExecutionData 数据文件
     * @param coberturaCoveredFactory 工厂类
     */
    public void analyzerAll(final String classFile,final CoberturaExecutionData coberturaExecutionData,final CoberturaCoveredFactory coberturaCoveredFactory){
        File tempFile=new File(classFile);
        if(tempFile.isDirectory()){
            File[] files = tempFile.listFiles();
            if (files != null) {
                for (File file : files) {
                    analyzerAll(file.getAbsolutePath(),coberturaExecutionData,coberturaCoveredFactory);
                }
            }
        }else{
            if(classFile.indexOf(".class")!=-1) {
                analyzer(classFile, coberturaExecutionData, coberturaCoveredFactory);
            }
        }
    }
    /**
     * 分析字节码
     * @param classFile
     */
    public void analyzer(final String classFile,final CoberturaExecutionData coberturaExecutionData,final CoberturaCoveredFactory coberturaCoveredFactory) {
        ClassReader cr = null;
        FileInputStream fis=null;
        ClassWriter cw=null;
        try {
            byte[] source = new byte[(int) new File(classFile).length()];
            fis= new FileInputStream(classFile);
            fis.read(source);
            final long classId= Crc64.crc64Long(source);
            cr = new ClassReader(source);
            cw= new ClassWriter(cr, ClassWriter.COMPUTE_MAXS|ClassWriter.COMPUTE_FRAMES);
            boolean[] probes=coberturaExecutionData.get(classId);
            final CoberturaPackageCoveredImpl coberturaPackageCovered=new CoberturaPackageCoveredImpl();
            final CoberturaClassCoveredImpl coberturaClassCovered=new CoberturaClassCoveredImpl();
            CoberturaClassAnalyzer coberturaClassAnalyzer=new CoberturaClassAnalyzer(cw,probes,coberturaClassCovered);
            CoberturaClassProbeAdapter coberturaClassProbeAdapter=new CoberturaClassProbeAdapter(Opcodes.ASM9,coberturaClassAnalyzer,classId);
            cr.accept(coberturaClassProbeAdapter,0);
            coberturaPackageCovered.addClassCovered(coberturaClassCovered);
            coberturaPackageCovered.increase();
            coberturaCoveredFactory.addPackageCovered(coberturaPackageCovered);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(fis!=null){
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


}
